﻿@using System.Web
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>机构设置 - 薪酬发放登记</title>
    <!-- 引入样式和脚本 -->
    <script src="~/lib/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css">
    <script src="//unpkg.com/element-plus"></script>

    <style>
        a {
            text-decoration: none; /* 去除下划线 */
            color: #409EFF; /* 链接颜色 */
            cursor: pointer; /* 鼠标样式为指针 */
        }

            a:hover {
                text-decoration: underline; /* 鼠标悬停时显示下划线 */
            }

        body {
            background-color: #FFFFCC; /* 页面背景色 */
            font-family: "Microsoft YaHei", sans-serif;
        }

        .el-table {
            background-color: white; /* 表格白底 */
            margin-top: 15px;
        }

        .solid-table {
            border-collapse: collapse;
            width: 100%;
            table-layout: fixed;
        }

            .solid-table td, .solid-table th {
                border: 1px solid #333;
                padding: 8px;
                text-align: left;
                word-break: break-all;
            }

        .bj {
            background-color: #FFD553;
            font-weight: bold;
        }


        .error-input {
            border: 1px solid #f56c6c !important;
        }

        .page-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 15px;
        }


        /* 模态框内图片样式 */
        .modal-image {
            max-width: 100%;
            max-height: 500px;
            display: block;
            margin: 0 auto;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <!-- Vue 挂载点 -->
    <div id="app">
        <div class="page-header">
            <span>您正在做的业务是：人力资源--薪酬标准管理--薪酬发放登记</span>
            
        </div>
        <table style="width:100%">
            <tr>
                <td>
                    薪酬单编号:{{xcdbh}}
                </td>
                <td style="text-align:right">
                    <el-button type="primary" v-on:click="TJ">提交</el-button>
                    <el-button type="primary" onclick="history.back()">返回</el-button>
                </td>
            </tr>
        </table>
        <table style="width:100%">
            <tr>
                <td>本机构总人数:{{total}}， 基本薪酬总数:{{total2}}，实发总额:{{total3}}</td>
                <td style="text-align: right;">登记人:<input v-model="djr" readonly/>登记时间:<span>{{djsj}}</span></td>
            </tr>
        </table>

        <table class="solid-table">
            <thead>
                <tr class="bj">
                    <th v-for="(header, index) in salaryStandardDetailsHeaders" :style="{ width: getColumnWidth(index) }" :key="index">{{ header }}</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in tableData" :key="index">
                    <td>{{ index + 1 }}</td>
                    <td style="width:400px">{{ item.human_id || '无' }}</td>
                    <td>{{ item.human_name || '无' }}</td>
                    <td>
                        <!-- 添加点击事件，传递item的相关信息 -->
                        <a href="javascript:void(0)" v-on:click="openDetailModal(item)">详细内容</a>
                    </td>
                    <td>
                        <input style="width:100px; background-color: transparent; outline: none;"
                               v-model.number="item.jl_amount"
                               v-on:click="handleInput0(index, 'jl_amount')"
                               v-on:input="handleInput(index, 'jl_amount')"
                               :name="'jl' + index"
                               type="number"
                               placeholder="0"
                               min="0"
                               step="0.01"
                               :class="{'error-input': isNaN(item.jl_amount)}" />
                    </td>
                    <td>
                        <input style="width:100px; background-color: transparent; outline: none;"
                               v-model.number="item.xsze_amount"
                               v-on:click="handleInput0(index, 'xsze_amount')"
                               v-on:input="handleInput(index, 'xsze_amount')"
                               :name="'xsze' + index"
                               type="number"
                               placeholder="0"
                               min="0"
                               step="0.01"
                               :class="{'error-input': isNaN(item.xsze_amount)}" />
                    </td>
                    <td>
                        <input style="width:100px; background-color: transparent; outline: none;"
                               v-model.number="item.ykje_amount"
                               v-on:click="handleInput0(index, 'ykje_amount')"
                               v-on:input="handleInput(index, 'ykje_amount')"
                               :name="'ykje' + index"
                               type="number"
                               placeholder="0"
                               min="0"
                               step="0.01"
                               :class="{'error-input': isNaN(item.ykje_amount)}" />
                    </td>
                    <td>
                        <input style="width:100px; background-color: transparent; border:none; outline: none;"
                               :name="'sum' + index"
                               v-model="item.paid_salary_sum"
                               readonly
                               :class="{'error-input': isNaN(parseFloat(item.paid_salary_sum))}" />
                    </td>
                </tr>
            </tbody>
        </table>

        <!-- 详细内容模态框 -->
        <el-dialog v-model="detailModalVisible" title="薪酬详细内容" :width="500" center :before-close="handleDetailClose">
            <table class="solid-table">
                <tr v-for="(item, index) in tableData2" :key="index">
                    <td>{{item.item_name}}</td>
                    <td>{{item.salary}}</td>
                </tr>
            </table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-on:click ="handleDetailClose">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <script type="text/javascript">
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        const { createApp, ref, onMounted, onUnmounted } = Vue;
        const app = createApp({
            setup() {
                const tableData = ref([]);
                const tableData2 = ref([]);
                const salaryStandardDetailsHeaders = ref(['序号', '档案编号', '姓名', '薪酬基本明细', '奖励金额', '销售绩效总额', '应扣金额', '实发金额']);
                const kf_id = ref('@ViewBag.kf_id');
                const sk_id = ref('@ViewBag.sk_id');
                const tk_id = ref('@ViewBag.tk_id');
                const total = ref(0);
                const total2 = ref('0.00');
                const total3 = ref('0.00');
                const djr = ref("@Context.Session.GetString("PName")");
                const xcdbh = ref();

                const djsj = ref(formatDateTime(new Date()));
                let timer = null;

                // 初始化计时器
                function initTimer() {
                    // 每秒执行一次
                    timer = setInterval(() => {
                        // 更新时间
                        djsj.value = formatDateTime(new Date());
                    }, 1000);
                }

                // 组件卸载时清除计时器
                onUnmounted(() => {
                    if (timer) {
                        clearInterval(timer);
                        timer = null;
                    }
                });
                //console.info(djr.value);

                // 模态框相关状态
                const detailModalVisible = ref(false);

                // 返回上一页
                const zz = ref(0);
                const zz2 = ref(0);
                const zz3 = ref(0);

                function getColumnWidth(file){
                    if(file == 1){
                        return '203px'
                    }
                    return 'auto'
                }
                // 处理输入事件并更新计算
                function handleInput0(rowIndex, fieldName) {

                    const currentRow = tableData.value[rowIndex];
                    //console.info(currentRow);
                    if(fieldName == "jl_amount")
                    {
                        zz.value = parseFloat(currentRow.jl_amount) || 0;
                    }
                    if(fieldName == "xsze_amount")
                    {
                        zz2.value = parseFloat(currentRow.xsze_amount) || 0;
                    }
                    if(fieldName == "ykje_amount")
                    {
                        zz3.value = parseFloat(currentRow.ykje_amount) || 0;
                    }
                }
                function handleInput(rowIndex, fieldName) {
                    console.info(fieldName)
                    if (rowIndex < 0 || rowIndex >= tableData.value.length) {
                        console.error('无效的行索引:', rowIndex);
                        return;
                    }

                    const currentRow = tableData.value[rowIndex];

                    // 确保所有金额字段为有效数字
                    const jlValue = parseFloat(currentRow.jl_amount) || 0;
                    const xszeValue = parseFloat(currentRow.xsze_amount) || 0;
                    const ykjeValue = parseFloat(currentRow.ykje_amount) || 0;
                    const pssValue = parseFloat(currentRow.paid_salary_sum) || 0;

                    // 计算实发金额（奖励金额 + 销售绩效总额 - 应扣金额）
                    let paidSalarySum = pssValue;
                    if(fieldName == "jl_amount")
                    {
                        paidSalarySum = pssValue-zz.value + jlValue;
                    }
                    if(fieldName == "xsze_amount")
                    {
                        paidSalarySum = pssValue-zz2.value + xszeValue;
                    }
                    if(fieldName == "ykje_amount")
                    {
                        paidSalarySum = pssValue+zz3.value - ykjeValue;
                    }



                    zz.value = jlValue;
                    zz2.value = xszeValue;
                    zz3.value = ykjeValue;
                    // 更新实发金额（处理NaN并格式化）
                    currentRow.paid_salary_sum = isNaN(paidSalarySum) ? '0.00' : paidSalarySum.toFixed(2);
                    // 重新计算总计
                    updateTotals();
                }

                // 更新总计
                function updateTotals() {
                    let totalCount = tableData.value.length;
                    let totalSalary = 0;
                    let totalPaid = 0;

                    tableData.value.forEach(item => {
                        totalSalary += parseFloat(item.salary_sum) || 0;
                        totalPaid += parseFloat(item.paid_salary_sum) || 0;
                    });

                    // 格式化总计并处理NaN
                    total.value = totalCount;
                    total2.value = isNaN(totalSalary) ? '0.00' : totalSalary.toFixed(2);
                    total3.value = isNaN(totalPaid) ? '0.00' : totalPaid.toFixed(2);
                }

                // 打开详细内容模态框
                function openDetailModal(item) {
                    // 这里假设图片路径存储在item.detail_image字段中
                    // 实际应用中请根据后端返回的字段名调整
                    //console.info(item.salary_standard_id);
                    axios.get(`/SDM_insert/Index6?ss_id=${item.salary_standard_id}`)
                        .then(res => {
                            tableData2.value = res.data.zhi;
                            
                        })
                        .catch(err => {
                            console.error('数据获取失败', err);
                            ElMessage.error('数据获取失败，请联系管理员');
                        });
                    detailModalVisible.value = true;
                }

                // 关闭详细内容模态框
                function handleDetailClose() {
                    detailModalVisible.value = false;
                }

                let counter = 0;
                function Digits() {
                    // const array = new Uint32Array(1);
                    // window.crypto.getRandomValues(array);
                    // const randomNumber = array[0] % Math.pow(10, 10);
                    // return randomNumber.toString().padStart(10, '0');
                    const timestamp = Math.floor(Date.now() / 1000);
                    // 取时间戳的后8位
                    const timestampPart = timestamp.toString().slice(-8);

                    // 同一秒内使用计数器（0-99）
                    counter = (counter + 1) % 100;
                    const counterPart = counter.toString().padStart(2, '0');

                    // 组合成10位数字
                    return timestampPart + counterPart;
                }
                // 填充数据并初始化
                function fetchData() {
                    axios.get(`/SDM_insert/Index5?kf_id=${kf_id.value}&sk_id=${sk_id.value}&tk_id=${tk_id.value}`)
                        .then(res => {
                            console.log('数据获取成功', res.data);
                            if (res.data.zhi && Array.isArray(res.data.zhi)) {
                                // 初始化数据，直接使用后端返回的paid_salary_sum
                                tableData.value = res.data.zhi.map(item => {
                                    // 确保数值字段有效，并添加图片路径字段（假设后端返回）
                                    return {
                                        ...item,
                                        jl_amount: parseFloat(item.jl_amount) || 0,
                                        xsze_amount: parseFloat(item.xsze_amount) || 0,
                                        ykje_amount: parseFloat(item.ykje_amount) || 0,
                                        // 假设detail_image是后端返回的图片路径字段
                                        detail_image: item.detail_image || '',
                                        // 直接使用后端返回的paid_salary_sum
                                        paid_salary_sum: parseFloat(item.paid_salary_sum)?.toFixed(2) || '0.00'
                                    };
                                });
                                xcdbh.value = "HS135" + Digits();
                                updateTotals();
                            } else {
                                tableData.value = [];
                                updateTotals();
                                ElMessage.warning('获取的数据格式不正确');
                            }
                        })
                        .catch(err => {
                            console.error('数据获取失败', err);
                            ElMessage.error('数据获取失败，请联系管理员');
                        });
                }
                function insertTitle(){
                    // 验证数据（确保有数据可提交）
                    if (tableData.value.length === 0) {
                        ElMessage.warning('没有可提交的薪酬记录');
                        return;
                    }

                    // 准备提交的数据（包含表格数据、登记人、时间）
                    const submitData = {
                        list: tableData.value,
                        //登记人
                        djr: djr.value,
                        //登记时间
                        djsj: djsj.value,
                        //单编号
                        xdh : xcdbh.value,

                        kf_id : kf_id.value,
                        sk_id : sk_id.value,
                        tk_id : tk_id.value
                    };

                    console.log('待提交数据:', submitData); // 调试用，查看数据是否正确

                    axios.post('/SDM_insert/Insert', submitData, {
                        headers: {
                            'Content-Type': 'application/json' // 明确传递 JSON 格式
                        }
                    })
                    .then(res => {
                        if(res.data.zhi >0){
                            //history.back();
                            parent.mainFrame.location.href='@Url.Action("Index", "SDM_insert")'
                            ElementPlus.ElMessage.success('提交成功');

                        }else{
                            ElementPlus.ElMessage.error('提交失败');
                        }
                        //console.info(res.data.zhi);
                    })
                    .catch(err => {
                        console.error('提交错误:', err);
                        if (err.response) {
                            console.error('状态码:', err.response.status);
                            console.error('响应内容:', err.response.data);
                        }
                        ElMessage.error('网络错误，请重试');
                    });
                }
                function TJ() {
                    ElementPlus.ElMessageBox.confirm(
                        `确定通过吗？`,
                        '是否通过',
                        {
                            confirmButtonText: '通过',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    )
                    .then(() => {
                        insertTitle();
                    })
                    .catch(() => {
                        ElementPlus.ElMessage.info('已取消添加');
                    });
                    
                }

                // 组件挂载时加载数据
                onMounted(() => {
                    fetchData();
                    initTimer();
                });

                return {
                    tableData,
                    tableData2,
                    salaryStandardDetailsHeaders,
                    kf_id,
                    sk_id,
                    tk_id,
                    total,
                    total2,
                    total3,
                    handleInput0,
                    handleInput,
                    fetchData,
                    getColumnWidth,
                    detailModalVisible,
                    openDetailModal,
                    handleDetailClose,
                    djr,
                    djsj,
                    TJ,
                    xcdbh
                };
            }
        });

        app.use(ElementPlus).mount('#app');
    </script>
</body>
</html>